package com.zhihao.takeaway.controller;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class RedisController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private Redisson redisson;

    @GetMapping("/redis/get/{key}")
    public Object get(@PathVariable("key")String key){

        // 先从缓存获取数据，如果有则直接返回
//                          若无，则查询mysql，并将数据设置到缓存
//        Object obj = redisTemplate.opsForValue().get(key);
//        if(obj == null){
//            synchronized (this.getClass()){
//                obj = redisTemplate.opsForValue().get(key);
//                if(obj == null){
//                    log.debug("-------->查询数据库.............");
////                    查询数据库
//                    User user = UserMapper.selectById(id);
//                    redisTemplate.opsForValue().set(key,emp);
//                    return emp;
//                }else{
//                    log.debug("---------->查询缓存。。。。。。。。。。");
//                }
//            }
//        }else{
//            log.debug("-——————>查询缓存>>>>>>>>>>>>>>>");
//        }
        return redisTemplate.opsForValue().get(key);
    }

    @PostMapping("/redis/set/{key}/{value}")
    public Object set(@PathVariable("key")String key,
                      @PathVariable("value")String value){

        redisTemplate.opsForValue().set(key, value);
        return "set success";
    }

    // 限量抢购
    @RequestMapping("/deduct_stock")
    public String deductStock() throws InterruptedException {
        String lockKey = "product_001";
        //            获取到这把锁
        RLock redissonLock = redisson.getLock(lockKey);
        String clientId = UUID.randomUUID().toString();
        try {
            //            Boolean result = redisTemplate.opsForValue().setIfAbsent("locakKey","zhuge");
//            这个 key 在用户那边最多待10s，超时，redis会主动清理掉
//            redisTemplate.expire("localKey",10, TimeUnit.SECONDS);
//            Boolean result = redisTemplate.opsForValue().setIfAbsent(lockKey, clientId, 10, TimeUnit.SECONDS);
//            if (!result) {
//                return "error";
//            }
//            设置锁的超时时间
            redissonLock.lock(30,TimeUnit.SECONDS);
            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
            if(stock>0){
                int realStock = stock -1;
                redisTemplate.opsForValue().set("stock",realStock+"");
                System.out.println("扣除成功，剩余库存："+realStock+"");
            }else{
                System.out.println("扣除失败，库存不足");
            }
        } finally {
//            if(clientId.equals(stringRedisTemplate.opsForValue().get(lockKey))) {
//                redisTemplate.delete("localKey");
//            }
            redissonLock.unlock();
        }
        return "end";
    }
}
